package handledb;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public class ResultMap {
    private String[] rowNames = null;
    private String[][] value = null;
    private int indexs = -1;
    private int len = 0;
    private int length = 0;
    public int rowSize = 0;
    public int colSize = 0;

    public ResultMap() {

    }

    public ResultMap(ResultSet rs) {
        ResultSetMetaData rsmd;
        try {
            rsmd = rs.getMetaData();
            rowSize = length = rsmd.getColumnCount();
            rowNames = new String[length];
            for (int i = 0; i < length; i++) {
                rowNames[i] = rsmd.getColumnName(i + 1);
            }
            if (rs.last()) {
                len = rs.getRow();
                rs.beforeFirst();
            }
            value = new String[len][length];
            int j = 0;
            while (rs.next()) {
                for (int i = 0; i < length; i++) {
                    value[j++][i] = rs.getString(rowNames[i]);
                }
            }
            colSize = len = j;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void rest() {
        indexs = -1;
    }

    public boolean next() {
        indexs++;
        if (indexs < len) {
            return true;
        } else {
            return false;
        }
    }

    public String getValue(int index) {
        return value[indexs][index];
    }

    public String getRowName(int index) {
        return rowNames[index];
    }

    public String getValue(String rowName) {
        for (int i = 0; i < length; i++) {
            if (rowNames[i].equals(rowName)) {
                return value[indexs][i];
            }
        }
        return null;
    }
}
